package cn.yhjz.live.trans;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Data
@Slf4j
public class TransPushFFMPEG implements ITransPush {
    private String sourceUrl;
    private String sourceHash;
    private boolean running = false;
    private static final String TARGET_URL = "http://localhost:8888/live/push/";

    public static final Map<String, Process> processMap = new ConcurrentHashMap<>();

    public void setSourceUrl(String sourceUrl) {
        this.sourceUrl = sourceUrl;
        int hash = this.sourceUrl.hashCode();
        this.sourceHash = Integer.toString(hash);
    }

    @Override
    public void start() {
        if (running) {
            return;
        }
        if (StringUtils.isEmpty(this.sourceUrl)) {
            throw new RuntimeException("请提供sourceUrl");
        }
        new Thread(() -> {
            try {
                running = true;
                Process process = new ProcessBuilder(
                        "ffmpeg", "-thread_queue_size", "128", "-i", sourceUrl, "-q", "0", "-f", "mpegts", "-codec:v",
                        "mpeg1video", TARGET_URL + this.sourceHash, "-loglevel", "quiet").start();
                log.info("开启ffmpeg进程");
                processMap.put(sourceHash, process);
                log.info("ffmpeg进程自动结束,{}");
            } catch (IOException e) {
                log.error("启动直播进程失败,{}", e);
            }
        }).start();
    }

    @Override
    public void stop() {
        Process process = processMap.get(sourceHash);
        if (process != null && process.isAlive()) {
            process.destroy();
        }
        running = false;
    }
}
